<template>
  <div class="chat-container">
    <el-tooltip content="打开侧边栏" placement="left" popper-append-to-body>
      <el-button
        v-if="!drawer"
        type="primary"
        circle
        @click="drawer = true"
        class="floating-button"
      >
        <i class="el-icon-plus"></i>
      </el-button>
    </el-tooltip>

    <el-drawer
      title="会话列表"
      v-model="drawer"
      direction="rtl"
      size="30%"
      :visible.sync="drawer"
      custom-class="custom-drawer"
    >
      <template #header>
        <div class="drawer-header">
          <span>会话列表</span>
          <el-button
            type="primary"
            size="small"
            @click="createNewConversation"
            class="new-conversation-btn"
          >
            <i class="el-icon-plus"></i> 新建会话
          </el-button>
        </div>
      </template>
      <template #close>
        <el-button type="text" @click="drawer = false">关闭</el-button>
      </template>
      <div v-for="(item, index) in conversationList" :key="index">
        <h3>{{ item.date }}</h3>
        <ul class="conversation-list">
          <li
            v-for="conversation in item.conversations"
            :key="conversation.id"
            :class="{ active: activeConversationId === conversation.id }"
            @click="loadConversation(conversation.id)"
            @mouseover="hoverConversationId = conversation.id"
            @mouseleave="hoverConversationId = null"
          >
            <span>{{ conversation.name }}</span>
          </li>
        </ul>
      </div>
    </el-drawer>

    <!-- 聊天主界面 -->
    <div class="chat-main" v-if="activeConversationId">
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(message, index) in currentMessages"
          :key="index"
          :class="[
            'message',
            message.informationType === 1 ? 'user-message' : 'ai-message',
          ]"
        >
          <div class="message-content">
            <div v-if="message.informationType === 1" class="message-header">
              <span class="message-time">{{
                formatMessageTime(message.createTime)
              }}</span>
              <span class="message-sender">You</span>
            </div>
            <div v-else class="message-header">
              <span class="message-sender">AI Assistant</span>
              <span class="message-time">{{
                formatMessageTime(message.createTime)
              }}</span>
            </div>
            <div
              class="message-text"
              v-html="formatMessageText(message.information)"
            ></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 没有选中会话时的提示 -->
    <div class="empty-chat" v-else>
      <p>请从左侧选择一个会话或创建新会话</p>
    </div>

    <div class="input-box">
      <div class="input-container">
        <el-input placeholder="请输入您的问题" v-model="inputValue"></el-input>
        <el-button type="primary" style="margin-left: 10px;" @click="handleSendMessage">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import req from "@/request";
import { ElMessage, ElTooltip } from "element-plus";
import { marked } from "marked";

// 会话列表和当前会话数据
const conversationList = ref([]);
const activeConversationId = ref(null);
const hoverConversationId = ref(null);
const currentMessages = ref([]);
const drawer = ref(true);
const inputValue = ref("");
const currentId = ref("");

//发送消息
const handleSendMessage = async () => {
  if (!inputValue.value) {
    ElMessage.warning("请输入内容");
  }
  try {
    const res = await req.post("/ai/chat", {
      message: inputValue.value,
      conversationId: currentId.value,
    });
    currentMessages.value.push(res.data)
  } catch (error) {
    console.error("发送消息失败：", error);
  } finally {
    loadConversation(currentId.value);
    inputValue.value = "";
  }
};

// 创建新会话
const createNewConversation = async () => {
  try {
    await req.get("/conversation/save");
    ElMessage.success("创建会话成功");
    // 刷新会话列表
    await getConversationList();
  } catch (error) {
    console.error("创建会话失败：", error);
    ElMessage.error("创建会话失败");
  }
};

// 获取会话列表
const getConversationList = async () => {
  try {
    const res = await req.get("/conversation/getList");
    conversationList.value = res.data;

    // 自动选择第一个会话
    if (
      conversationList.value.length > 0 &&
      conversationList.value[0].conversations.length > 0
    ) {
      const firstConversationId = conversationList.value[0].conversations[0].id;
      currentId.value = firstConversationId;
      await loadConversation(firstConversationId);
    }
  } catch (error) {
    console.error("获取会话信息失败：", error);
    ElMessage.error("获取会话列表失败");
  }
};

// 加载会话内容
const loadConversation = async (conversationId) => {
  currentId.value = conversationId;
  try {
    activeConversationId.value = conversationId;
    const res = await req.get(`/conversationLogs/getList/${conversationId}`);
    if (res.data && res.data.length > 0) {
      currentMessages.value = res.data;
      // 滚动到底部
      nextTick(() => {
        const container = document.querySelector(".chat-messages");
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    } else {
      currentMessages.value = [];
    }

    drawer.value = false;
  } catch (error) {
    console.error("获取会话内容失败：", error);
    ElMessage.error("获取会话内容失败");
  }
};

// 格式化消息时间
const formatMessageTime = (timeArray) => {
  if (!timeArray || timeArray.length < 6) return "";
  const [year, month, day, hour, minute, second] = timeArray;
  const date = new Date(year, month - 1, day, hour, minute, second);
  return date.toLocaleTimeString();
};

// 格式化消息文本（处理Markdown等格式）
const formatMessageText = (text) => {
  // 使用marked解析Markdown
  return marked(text);
};

onMounted(() => {
  getConversationList();
});
</script>

<style scoped>
.chat-container {
  position: relative;
  display: flex;
  height: 100vh;
}

.chat-main {
  padding: 0 180px;
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
}

.input-box {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 10px;
  background-color: #fff;

  .input-container {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 830px;
    padding: 10px;
    background-color: #f3f4f6;
    border-radius: 10px;
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fff;
  &::-webkit-scrollbar {
    display: none;
  }
}

.message {
  margin-bottom: 15px;
  display: flex;
  margin-bottom: 55px;
}

.message-content {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 8px;
  position: relative;
}

.user-message {
  justify-content: flex-end;
}

.user-message .message-content {
  background-color: #e1f5fe;
}

.ai-message {
  justify-content: flex-start;
}

.ai-message .message-content {
  background-color: #f5f5f5;
  border: 1px solid #e0e0e0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
  color: #666;
}

.message-text {
  line-height: 1.5;
}

.empty-chat {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
}

.floating-button {
  position: fixed;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
  z-index: 999;
  transition: all 0.3s ease;
}

.floating-button:hover {
  transform: translateY(-50%) scale(1.1);
}

.conversation-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.conversation-list li {
  padding: 10px 15px;
  cursor: pointer;
  border-radius: 4px;
  margin-bottom: 5px;
  transition: all 0.2s ease;
}

.conversation-list li:hover {
  background-color: #f5f5f5;
}

.conversation-list li.active {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
}

/* 新建会话按钮样式 */
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 16px;
}

.new-conversation-btn {
  background-color: #4f46e5;
  border-color: #4f46e5;
  color: white;
  border-radius: 8px;
  padding: 8px 12px;
  transition: all 0.2s ease;
}

.new-conversation-btn:hover {
  background-color: #4338ca;
  border-color: #4338ca;
  transform: translateY(-1px);
}

.new-conversation-btn i {
  margin-right: 4px;
}
</style>
